// src/components/MenuPart/MenuPart.js
import React, { useContext, useEffect, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { MenuContext } from '../MenuContext/MenuContext'
import {
    ContainerOutlined,
    DesktopOutlined,
    PieChartOutlined,
} from '@ant-design/icons'
import { Menu } from 'antd'
import './MenuPart.css'

const items = [
    {
        key: '1',
        icon: <PieChartOutlined />,
        label: 'Option 1',
        path: '/',
    },
    {
        key: '2',
        icon: <DesktopOutlined />,
        label: 'Option 2',
        path: '/contact',
    },
    {
        key: '3',
        icon: <ContainerOutlined />,
        label: 'Option 3',
        path: '/about',
    },
]

const findParentKeys = (items, key) => {
    let result = []
    const find = (items, parentKey) => {
        for (const item of items) {
            if (item.key === key) {
                if (parentKey) {
                    result.push(parentKey)
                }
                return true
            }
            if (item.children) {
                if (find(item.children, item.key)) {
                    if (parentKey) {
                        result.push(parentKey)
                    }
                    return true
                }
            }
        }
        return false
    }
    find(items, null)
    return result
}

const MenuPart = () => {
    const navigate = useNavigate()
    const location = useLocation()
    const { setSelectedItem } = useContext(MenuContext)
    const [defaultSelectedKeys, setDefaultSelectedKeys] = useState(['1']) // 默认高亮第一个选项
    const [defaultOpenKeys, setDefaultOpenKeys] = useState([])

    useEffect(() => {
        const currentPath = location.pathname
        const item = items.find(i => i.path === currentPath)
        if (item) {
            setSelectedItem(item)
            setDefaultSelectedKeys([item.key])
            const parentKeys = findParentKeys(items, item.key)
            setDefaultOpenKeys(parentKeys)
        } else {
            setSelectedItem(null)
            setDefaultSelectedKeys(['1']) // 默认高亮第一个选项
            setDefaultOpenKeys([])
        }
    }, [location.pathname, setSelectedItem])

    const handleMenuClick = (e) => {
        const item = items.find(i => i.key === e.key)
        if (item && item.path) {
            navigate(item.path)
        }
    }

    return (
        <div className='menu-part'>
            <h2 className='menu-title'>Menu</h2>
            <Menu
                selectedKeys={defaultSelectedKeys} // 使用 selectedKeys 而不是 defaultSelectedKeys
                openKeys={defaultOpenKeys} // 使用 openKeys 而不是 defaultOpenKeys
                mode="inline"
                theme="dark"
                items={items}
                className='menu'
                onClick={handleMenuClick}
            />
        </div>
    )
}

export default MenuPart